import React, { useState, useEffect } from 'react';
import {
  Text,
  View,
  Image,
  StyleSheet,
  FlatList,
  Dimensions,
  TouchableOpacity,
  Modal,
  ActivityIndicator,
  ScrollView,
  Alert
} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { Video } from 'expo-av';
import * as FileSystem from 'expo-file-system';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale'; // 导入中文本地化
import CommentModal from './CommentModal';
import { useNavigation } from 'expo-router';
import { router } from 'expo-router';
import { loadPosts } from '@/store/postSlice';
import store from '@/store/postindex';
import { addComment, addGood, follow, clearPosts } from '@/store/postSlice';
const SCREEN_WIDTH = Dimensions.get('window').width;

export default function Square() {
  const dispatch = useDispatch();
  useEffect(() => {
    store.dispatch(loadPosts()); // 加载存储的帖子
  }, [])
  const posts = useSelector((state) => state.post.posts);
  // console.log(posts, 'posts');

  let [postId, setPostId] = useState('')
  const cid = '6'
  useEffect(() => {
    posts.map((post, index) => ({
      ...post,
      id: post.id || `post-${index}-${Date.now()}`, // 如果没有 ID 或重复，则生成一个新 ID
    }));
  }, [])

  const navigateToUser = (userId) => {
    router.push(`/square/PostDetail?id=${userId}`)
  };
  const [mediaInfo, setMediaInfo] = useState({});
  const [likeStatus, setLikeStatus] = useState({}); // 管理每条帖子的点赞状态
  const [showImagePreviewModal, setShowImagePreviewModal] = useState(false);
  const [currentImageIndex, setCurrentImageIndex] = useState(0); // 当前显示的图片索引
  // 图片点击处理
  const handleImageClick = (index) => {
    setCurrentImageIndex(index);
    setShowImagePreviewModal(true); // 显示图片预览
  };
  // 点赞/取消赞
  const handleLikeToggle = (postId) => {
    setLikeStatus((prev) => ({
      ...prev,
      [postId]: !prev[postId], // 切换对应帖子点赞状态
    }));
    const newGood = {
      id: cid
    }
    dispatch(addGood({ postid: postId, good: newGood }))
  };

  const [showCommentModal, setShowCommentModal] = useState(false); //控制评论的弹窗
  const [isLoading, setIsLoading] = useState(false); // 加载动画状态
  const [followedStatus, setFollowedStatus] = useState({}); // 管理每条帖子的关注状态
  const [showFollowedMessage, setShowFollowedMessage] = useState(false); // "已关注" 提示框状态
  const [showMoreModal, setShowMoreModal] = useState(false); // 控制更多弹出框

  // 点击关注按钮
  const handleFollow = (postId) => {
    setIsLoading(true); // 显示加载动画
    setTimeout(() => {
      setIsLoading(false); // 隐藏加载动画
      setShowFollowedMessage(true); // 显示"已关注"提示
      // 关注逻辑
      const newFocus = {
        id: postId
      }
      const newFans = {
        id: cid
      }
      dispatch(follow({ postid: postId, focus: newFocus, userId: cid, fans: newFans }))

      setFollowedStatus((prev) => ({
        ...prev,
        [postId]: true, // 设置该条数据为已关注
      }));

      setTimeout(() => {
        setShowFollowedMessage(false); // 隐藏"已关注"提示
      }, 2000);
    }, 2000);
  };
  // 创建一个静态资源的映射对象
  const imageMap = {
    'v1.jpg': require('../../assets/images/v1.jpg'),
    'v2.jpg': require('../../assets/images/v2.jpg'),
    'v3.jpg': require('../../assets/images/v3.jpg'),
    'v4.jpg': require('../../assets/images/v4.jpg'),
    'v5.jpg': require('../../assets/images/v5.jpg'),
    // 更多的静态图片映射...
  };
  useEffect(() => {
    const checkMediaFiles = async () => {
      const mediaStatus = {};
      for (const post of posts) {
        if (post.media && post.media.length > 0) {
          const uri = post.media[0].uri;
          const info = await FileSystem.getInfoAsync(uri);
          mediaStatus[uri] = info.exists;
        }
      }
      setMediaInfo(mediaStatus);
    };

    checkMediaFiles();
  }, [posts]);
  // 更多
  const handleMoreModalToggle = () => {
    if (showMoreModal) {
      setShowMoreModal(false);
    } else {
      setTimeout(() => {
        setShowMoreModal(true);
      }, 100); // 延时，防止快速点击导致重复打开
    }
  };
  // 点击评论图片
  const handelCom = (id) => {
    postId = id
    setPostId(id)
    setShowCommentModal(true)
  }

  return (
    <View style={styles.container}>
      <FlatList
        data={posts}
        keyExtractor={(item) => item.id}
        showsVerticalScrollIndicator={false}
        renderItem={({ item }) => {
          const mediaExists = mediaInfo[item.media[0]?.uri] ?? false;
          // const relativeTime = formatDistanceToNow(new Date(item.createTime), { addSuffix: true });
          // 将 createTime 转换为 Date 对象
          const time = new Date(item.createTime);
          const isValidDate = !isNaN(time.getTime()); // 检查时间是否有效
          const isLiked = likeStatus[item.id] || false; // 获取当前帖子的点赞状态
          const isFollowed = followedStatus[item.id] || false;

          return (
            <View style={styles.card}>
              <View style={styles.header}>

                <View style={styles.imgsAndname}>
                  <Image source={{ uri: item.avatar }} style={styles.avatar} />
                  <View style={styles.nameAndgenderAndcountryAndtime}>
                    <View style={styles.genderAndname}>
                      <Text style={styles.name}>{item.name}</Text>
                      {item.gender === "男" ? (
                        <Image
                          source={require("../../assets/images/male.png")}
                          style={styles.gender}
                        />
                      ) : (
                        <Image
                          source={require("../../assets/images/female.png")}
                          style={styles.gender}
                        />
                      )}
                    </View>
                    <View style={styles.countryAndtime}>
                      <Text style={styles.location}>
                        {/* <Translate i18nKey="United States">
                        </Translate> */}
                        {item.country}
                      </Text>

                      {isValidDate ? (
                        <Text style={styles.locations}>
                          {formatDistanceToNow(time, { locale: zhCN })
                            .replace("大约", "")
                            .split(" ")}
                          前
                        </Text>
                      ) : (
                        <Text style={styles.locations}>时间无效</Text>
                      )}
                    </View>
                  </View>
                </View>

                <View style={styles.imgs}>
                  {/* <TouchableOpacity>
                    <Image source={require('../../assets/images/plus.png')} style={styles.plus} />
                  </TouchableOpacity> */}
                  {/* !item.focus.some((item) => item.id === cid) */}
                  {/* followedStatus[item.id] */}
                  {!item.fans.some((item) => item.id === cid) && (
                    <TouchableOpacity onPress={() => handleFollow(item.id)}>
                      <Image
                        source={require('../../assets/images/plus.png')}
                        style={styles.plus}
                      />
                    </TouchableOpacity>
                  )}
                  <TouchableOpacity onPress={handleMoreModalToggle}>
                    <Image
                      source={require("../../assets/images/more.png")}
                      style={styles.more}
                    />
                  </TouchableOpacity>
                </View>
              </View>
              {/* header结束 */}
              <Text style={styles.content}>{item.content}</Text>
              {/* 路由跳转 */}
              <TouchableOpacity

                onPress={() => {
                  console.log('Clicked item ID:', item.id); // 检查点击时的 id
                  console.log('类型', typeof (item.id));

                  navigateToUser(item.id)
                }}
              >
                {mediaExists && (
                  <View style={styles.mediaContainer}>
                    {item.media[0]?.type === "image" && (
                      <Image
                        source={
                          item.media[0].uri.startsWith("file://")
                            ? { uri: item.media[0].uri } // 本地文件路径
                            : imageMap[item.media[0].uri.split('/').pop()] || { uri: item.media[0].uri } // 静态资源
                        }
                        style={styles.media}
                      />
                    )}
                    {item.media[0]?.type === "video" && (
                      <Video
                        source={
                          item.media[0].uri.startsWith("file://")
                            ? { uri: item.media[0].uri } // 本地文件路径
                            : imageMap[item.media[0].uri.split('/').pop()] || { uri: item.media[0].uri } // 静态资源
                        }
                        style={styles.media}
                        useNativeControls
                        resizeMode="contain"
                        isLooping
                      />
                    )}
                  </View>
                )}
              </TouchableOpacity>

              {/* 图片预览 */}
              {/* {mediaExists && item.media.length > 0 && (
                <TouchableOpacity onPress={() => handleImageClick(0)}>
                  {item.media[0]?.type === 'image' && (
                    <Image
                      source={
                        item.media[0].uri.startsWith('file://')
                          ? { uri: item.media[0].uri }
                          : imageMap[item.media[0].uri.split('/').pop()] ||
                          { uri: item.media[0].uri }
                      }
                      style={styles.media}
                    />
                  )}
                  {item.media[0]?.type === 'video' && (
                    <Video
                      source={
                        item.media[0].uri.startsWith('file://')
                          ? { uri: item.media[0].uri }
                          : imageMap[item.media[0].uri.split('/').pop()] ||
                          { uri: item.media[0].uri }
                      }
                      style={styles.media}
                      useNativeControls
                      resizeMode="contain"
                      isLooping
                    />
                  )}
                </TouchableOpacity>
              )} */}
              {/* <Image source={require('@/assets/images/v1.jpg')}/> */}
              {/* 图片找不到的显示 */}
              {!mediaExists && <Text style={{ color: 'red' }}>Media not found</Text>}
              {/* 赞和评论 */}
              <View style={styles.goodAndComment}>
                <View style={styles.goods}>
                  {
                    item.goods.some((item) => item.id === cid) ? (
                      <TouchableOpacity onPress={() => handleLikeToggle(item.id)}>
                        <Image source={require('../../assets/images/good.png')} style={styles.good} />
                      </TouchableOpacity>
                    ) : (
                      <TouchableOpacity onPress={() => handleLikeToggle(item.id)}>
                        <Image source={require('../../assets/images/nogood.png')} style={styles.good} />
                      </TouchableOpacity>
                    )
                  }
                  <Text style={styles.goodNum}>{item.goods.length}人觉得很赞</Text>
                </View>
                <View style={styles.goods}>
                  <TouchableOpacity onPress={() => { handelCom(item.id) }}>
                    <Image source={require('../../assets/images/comment.png')} style={styles.good} />
                  </TouchableOpacity>
                  <Text style={styles.commentNum}>{item.comments.length}</Text>
                </View>
              </View>
              {/* 评论弹窗 */}
              <CommentModal
                postId={postId}
                visible={showCommentModal}
                onClose={() => setShowCommentModal(false)}
                route
              />

              {/* 加载动画 */}
              {isLoading && (
                <Modal transparent>
                  <View style={styles.loadingOverlay}>
                    <ActivityIndicator size="large" color="#00C7B8" />
                  </View>
                </Modal>
              )}
              {/* "已关注" 提示 */}
              {showFollowedMessage && (
                <Modal transparent>
                  <View style={styles.messageOverlay}>
                    <View style={styles.messageBox}>
                      <Text style={styles.messageText}>已关注</Text>
                    </View>
                  </View>
                </Modal>
              )}
              {/* 更多操作弹出框 */}
              <Modal
                transparent
                visible={showMoreModal}
                animationType="slide"
                onRequestClose={() => setShowMoreModal(false)}
              >
                <TouchableOpacity
                  style={styles.modalOverlay}
                  activeOpacity={1} // 避免透明背景可点击后穿
                  onPress={() => { }} // 点击背景关闭弹出框
                >
                  <View style={styles.moreOptions}>
                    <TouchableOpacity
                      onPress={() => {
                        console.log('举报功能触发');
                        setShowMoreModal(false); // 关闭弹框
                        // 在这里可以调用 Redux action 或其他逻辑
                        Alert.alert('举报成功', '举报已提交');
                      }}
                    >
                      <Text style={styles.optionText}>举报</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                      onPress={() => {
                        console.log('屏蔽功能触发');
                        setShowMoreModal(false); // 关闭弹框
                        // 在这里可以调用屏蔽的逻辑
                        Alert.alert("屏蔽成功", '已屏蔽该用户');
                      }}
                    >
                      <Text style={styles.optionText}>屏蔽</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => setShowMoreModal(false)}>
                      <Text style={[styles.optionText, styles.cancelText]}>取消</Text>
                    </TouchableOpacity>
                  </View>
                </TouchableOpacity>
              </Modal>

              {/* 图片预览Modal */}
              <Modal
                transparent
                visible={showImagePreviewModal}
                animationType="slide"
                onRequestClose={() => setShowImagePreviewModal(false)}
              >
                <TouchableOpacity
                  style={styles.modalOverlay}
                  onPress={() => setShowImagePreviewModal(false)} // 点击背景关闭弹出框
                >
                  <ScrollView
                    horizontal
                    pagingEnabled
                    contentContainerStyle={styles.imagePreviewScroll}
                  >
                    {item.media.map((mediaItem, index) => (
                      <View key={index} style={styles.imagePreviewContainer}>
                        {mediaItem.type === 'image' && (
                          <Image
                            source={
                              mediaItem.uri.startsWith('file://')
                                ? { uri: mediaItem.uri }
                                : imageMap[mediaItem.uri.split('/').pop()] || { uri: mediaItem.uri }
                            }
                            style={styles.imagePreview}
                          />
                        )}
                        {mediaItem.type === 'video' && (
                          <Video
                            source={
                              mediaItem.uri.startsWith('file://')
                                ? { uri: mediaItem.uri }
                                : imageMap[mediaItem.uri.split('/').pop()] || { uri: mediaItem.uri }
                            }
                            style={styles.imagePreview}
                            useNativeControls
                            resizeMode="contain"
                          />
                        )}
                      </View>
                    ))}
                  </ScrollView>
                </TouchableOpacity>
              </Modal>
            </View>
          );
        }}
      />
    </View >
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#f5f5f5", padding: 16 },
  card: {
    backgroundColor: "#fff",
    borderRadius: 8,
    padding: 16,
    marginBottom: 16,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  header: {
    flexDirection: "row",
    // alignItems: 'center',
    marginBottom: 8,
    height: 50,
  },
  nameAndgenderAndcountryAndtime: {
    marginTop: 5
  },
  imgsAndname: {
    flexDirection: "row",
    // alignItems: 'center',
    marginBottom: 4,
    // justifyContent: 'space-between',
    flex: 1,
  },
  plus: {
    width: 32,
    height: 20,
    borderRadius: 20,
    marginRight: 5
  },
  more: {
    width: 18,
    height: 22,
  },
  imgs: {
    flexDirection: 'row',
    height: 40,
    marginTop: 5
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginRight: 12,
  },
  genderAndname: {
    flexDirection: "row",
  },
  gender: {
    width: 20,
    height: 20,
    marginLeft: 5,
  },
  name: { fontWeight: "bold", fontSize: 16 },
  location: { fontSize: 12, color: "#666" },
  locations: { fontSize: 12, color: "#666", marginLeft: 8 },
  content: {
    fontSize: 14,
    color: "#333",
    marginBottom: 8,
  },
  mediaContainer: {
    marginTop: 8,
  },
  media: {
    width: SCREEN_WIDTH - 64,
    height: 200,
    borderRadius: 8,
    backgroundColor: "#ccc",
  },
  countryAndtime: {
    flexDirection: "row",
    // justifyContent: "space-between",
    marginTop: 4,
  },
  goodAndComment: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: 280
  },
  good: {
    width: 20,
    height: 20,
    marginLeft: 5,
    marginTop: 10
  },
  goods: {
    flexDirection: 'row'
  },
  goodNum: {
    fontSize: 12,
    color: '#666',
    marginLeft: 8,
    marginTop: 14
  },
  commentNum: {
    fontSize: 12,
    color: '#666',
    marginLeft: 8,
    marginTop: 12
  },
  loadingOverlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    // backgroundColor: 'rgba(0, 0, 0, 0.6)',
  },
  loadingText: {
    fontSize: 16,
    color: '#fff',
  },
  messageOverlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    // backgroundColor: 'rgba(0, 0, 0, 0.6)',
  },
  messageText: {
    fontSize: 14,
    color: '#ccc',
    marginTop: 10,
    marginLeft: 17
  },
  messageBox: {
    width: 80,
    height: 40,
    lineHeight: 40,
    textAlign: 'center',
    backgroundColor: 'rgb(0,0,0)',
    borderRadius: 10
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
    justifyContent: 'flex-end',
  },
  moreOptions: {
    backgroundColor: '#fff',
    padding: 16,
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
  },
  optionText: {
    fontSize: 18,
    color: '#333',
    paddingVertical: 12,
    textAlign: 'center',
  },
  cancelText: {
    color: '#999',
    fontWeight: 'bold',
  },
  imagePreviewScroll: {
    alignItems: 'center',
  },
  imagePreviewContainer: {
    width: SCREEN_WIDTH,
    justifyContent: 'center',
    alignItems: 'center',
  },
  imagePreview: {
    width: SCREEN_WIDTH,
    height: 300,
    resizeMode: 'contain',
  },
});
